﻿using AutoMapper;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.SupplierCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.SupplierCommandHandler
{

    /// <summary>
    /// 供应商管理查询命令处理
    /// </summary>
    public class SupplierQueryCommandHandler : IRequestHandler<SupplierQueryCommand, APIPaing<List<Supplier>>>
    {
        /// <summary>
        /// AutoMapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 仓储-供应商
        /// </summary>
        private readonly IBaseRepository<Supplier> supplierRepository;
        /// <summary>
        ///构造方法
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="supplierRepository"></param>
        public SupplierQueryCommandHandler(IMapper mapper, IBaseRepository<Supplier> supplierRepository)
        {
            this.mapper = mapper;
            this.supplierRepository = supplierRepository;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<APIPaing<List<Supplier>>> Handle(SupplierQueryCommand request, CancellationToken cancellationToken)
        {
            APIPaing<List<Supplier>> result = new APIPaing<List<Supplier>>();
            var list = supplierRepository.GetAll().Result.Where(o => o.IsDelete == 0);
            if (!string.IsNullOrEmpty(request.SupplierCode))
            {

                list = list.Where(o => o.SupplierCode == request.SupplierCode);
            }
            if (!string.IsNullOrEmpty(request.SupplierName))
            {
                list=list.Where(o=>o.SupplierName.Contains(request.SupplierName));
            }
            if (!string.IsNullOrEmpty(request.Status))
            {

                list = list.Where(o => o.Status == request.Status);
            }
            if (!string.IsNullOrEmpty(request.SupplierType))
            {

                list = list.Where(o => o.SupplierType==request.SupplierType);
            }
            if (!string.IsNullOrEmpty(request.City))
            {

                list = list.Where(o => o.City == request.City);
            }
            result.TotalCount = list.Count();
            result.PageCount = (int)Math.Ceiling((double)result.TotalCount / request.PageSize);
            list=list.OrderByDescending(o=>o.SupplierId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize);
            var data=mapper.Map<List<Supplier>>(list);
            result.Code = APIEnums.查询成功;
            result.Msg = APIEnums.查询成功.ToString();
            result.data = data;
            return await Task.FromResult(result);

        }
    }
}
